﻿using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using ProjectManApi.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BusinessEntity.xmglQuerryEntity;
using System.Data;
using BusinessEntity;
using BusinessRule;
using Newtonsoft.Json.Linq;
using System.Dynamic;

namespace ProjectManApi.Controllers.xmgl
{
    public class ProGaiSuanController : MvcControllerBase
    {
        private readonly INacosServerManager _serverManager;
        public ProGaiSuanController(INacosServerManager serverManager) : base(serverManager)
        {
            _serverManager = serverManager;
        }

        #region 导出


        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportGSList(string strxmid)//dynamic expjson
        {
            List<ColumnModel> cols = new List<ColumnModel>();
            //dts.Columns.Add("dxmc");
            //dts.Columns.Add("units");
            //dts.Columns.Add("nums");
            //dts.Columns.Add("prices");
            //dts.Columns.Add("gspsje");
            cols.Add(new ColumnModel() { Column = "bh", ExcelColumn = "编号" });
            cols.Add(new ColumnModel() { Column = "dxmc", ExcelColumn = "费用类名" });
            cols.Add(new ColumnModel() { Column = "units", ExcelColumn = "单位" });
            cols.Add(new ColumnModel() { Column = "nums", ExcelColumn = "数量" });
            cols.Add(new ColumnModel() { Column = "prices", ExcelColumn = "单价" });
            cols.Add(new ColumnModel() { Column = "gspsje", ExcelColumn = "费用" });
            cols.Add(new ColumnModel() { Column = "remark", ExcelColumn = "备注" });

            DataTable dts = await ProGaiSuanRule.GetGSListByXmid(strxmid);


            return File(await CProTZJHRule.GetExportListTS(dts, cols, BaseEditPower.TableName.概算, "概算申请列表"), "application/ms-excel", "采购申请列表.xls");
        }


        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ExportList(dynamic expjson)
        {

            JObject job = (JObject)expjson;

            List<string> ids = new List<string>();
            List<ColumnModel> cols = new List<ColumnModel>();

            if (null != job["ids"])
                ids = job["ids"].ToObject<string[]>().ToList();

            if (null != job["cols"])
                cols = job["cols"].ToObject<ColumnModel[]>().ToList();

            return File(await CProTZJHRule.GetExportList(ids, cols, BaseEditPower.TableName.概算, "概算申请列表"), "application/ms-excel", "采购申请列表.xls");
        }

        #endregion

        #region 查询，新增，修改,删除，采购申请

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSIndexList(string xmmc, string xmfl, string jsdw, string status, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "xmid")
        {
            try
            {
                ProGaiSuanQuerry querry = new ProGaiSuanQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;


                querry.Jsdw = jsdw;
                querry.Xmmc = xmmc;
                querry.Xmfl = xmfl;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;

                (DataTable, int) SelectTable = await ProGaiSuanRule.GetGSIndexList(querry, await GetDepId());//GetUserId()
                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        //选择概算明细列表 用作变更
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSIndexListN(string xmmc, string xmbm, string year, string dxmc, string xmfl, string jsdw, string gsmc, string status, string current = "1", string size = "20", string sort = "desc", string column = "xmid")
        {
            try
            {
                ProGaiSuanQuerryN querry = new ProGaiSuanQuerryN();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;


                querry.Jsdw = jsdw;
                querry.Xmmc = xmmc;
                querry.Xmfl = xmfl;
                querry.Status = status;
                querry.gsmc = dxmc;

                querry.xmbm = xmbm;
                querry.xmnf = year;

                if (!string.IsNullOrEmpty(querry.Status))
                {
                    querry.Status = "checked";
                }

                (DataTable, int) SelectTable = await ProGaiSuanRule.GetGSIndexListN(querry, await GetDepId());//GetUserId()
                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        [HttpGet]
        //[Authorize(Policy = "TestPolicy")]
        //[AllowAnonymous]
        public async Task<IActionResult> GetGSPCIndexList(string formCode,string xmid ,string xmmc, string jsdw, string status, string year, DateTime? begindate, DateTime? enddate, string current = "1", string size = "20", string sort = "desc", string column = "xmid")
        {
            try
            {
                ProGaiSuanPCQuerry querry = new ProGaiSuanPCQuerry();
                //基础属性
                querry.size = CommonHelper.ParseInt(size);
                querry.current = CommonHelper.ParseInt(current);
                querry.sort = sort;
                querry.column = column;


                querry.Jsdw = jsdw;
                querry.Xmmc = xmmc;
                querry.Xmnd = year;
                querry.Status = status;
                querry.Begindate = begindate;
                querry.Enddate = enddate;
                querry.xmid = xmid;

                (IEnumerable<dynamic>, int) SelectTable = await ProGaiSuanRule.GetGSPCIndexList(querry, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                _logger.Debug("调用审批" + list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug("审批返回" + spitems.ToJson());


                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        #endregion

        #region 概算录入（标段列表，查询单条概算，单项个数，需审核个数，审核中个数，新增修改概算，删除概算，概算变更）

        //这里是概算拆分的时候下面标段列表
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetDXListByXMid(string xmid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetDXListByXMid(xmid);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSDXList(string xmid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSDXList(xmid);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        //原概算拆分合并标段下面
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSDXListByGsid(string gsid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSDXListByGsid(gsid);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取概算树结构列表  lx = all  
        /// </summary>
        /// <param name="xmid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSTreeByXmid(string xmid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSTreeByXmid(xmid);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取概算树结构列表  lx = all  
        /// </summary>
        /// <param name="xmid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSTreeByXmidAudit(string xmid)
        {
            try
            {
                //查询已审核的
                var SelectTable = await ProGaiSuanRule.GetGSTreeByXmid(xmid, "ysh");
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取概算树结构列表
        /// </summary>
        /// <param name="pcid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSTreeByPCid(string pcid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSTreeByPCid(pcid);
                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取概算树结构列表和所属项目信息
        /// </summary>
        /// <param name="pcid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSInfoAndTreeByPCid(string pcid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSpcById(pcid);
                var pcnodetree = await ProGaiSuanRule.GetGSTreeByPCid(pcid);

                SelectTable.childs = pcnodetree;

                return Success(SelectTable);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 概算列表-固定单体pid=0,概算pid=固定单体id
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="xmid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSListByXmid(string xmid)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSListByXmid(xmid);

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }


        /// <summary>
        /// 根据id获取单条数据
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSById(string keyValue)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSById(keyValue);

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }
        /// <summary>
        /// 根据id获取单项个数
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetLXCountById(string keyValue)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetLXCountById(keyValue);

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 根据id获取概算个数
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSCountById(string keyValue)
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSCountById(keyValue);

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        ///// <summary>
        ///// 插入修改 这个方法不用了
        ///// </summary>
        ///// <param name="progs"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> InsertCProManageGS2(CProManageGS progs)
        //{
        //    try
        //    {
        //        await BusinessRule.ProGaiSuanRule.InsertCProManageGS(progs, GetUserId());

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        //return Fail("响应失败");
        //        return Fail(ex.Message);
        //    }
        //}

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="progs"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> AddOrUdpCProManageGS(dynamic progs)
        {
            string strope = "add";
            CProManageGS progse = null;

            try
            {
                JObject job = (JObject)progs;

                //获取方法
                strope = progs.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                progse = job["progs"].ToObject<CProManageGS>();



                if (strope != "add" && strope != "edit")// && strope != "submit"
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }



            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(progse.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProManageGS jhe = await TranstionRule.FindEntityByKey<CProManageGS>(progse.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    progse.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    string strid = CommonHelper.GetUniqueId().ToString();
                    progse.id = strid;
                    progse.createuser = GetUserId();

                    if (strlsope != "submit")
                        progse.status = BaseEditPower.GetSPEnumValue("待提交");
                    progse.remark = "1";

                    if (string.IsNullOrEmpty(progse.pid))
                    {
                        throw new Exception("概算信息pid不能为空");
                    }

                    if (string.IsNullOrEmpty(progse.pcid))
                    {
                        throw new Exception("概算信息pcid不能为空");
                    }

                    CProManageGS jhe = await TranstionRule.FindEntityByKey<CProManageGS>(progse.pid);
                    if (null == jhe)
                    {
                        throw new Exception("概算节点父类型不存在");
                    }
                    else
                    {
                        progse.xmid = jhe.xmid;

                        CProManageGSpc pc = await TranstionRule.FindEntityByKey<CProManageGSpc>(progse.pcid);
                        if (null != pc)
                        {
                            if (pc.status == "2")
                            {
                                throw new Exception("批次已审核，不能维护");
                            }
                        }
                        else
                        {
                            throw new Exception("节点所在的批次不存在");
                        }
                    }

                    //bool bsp = true;
                    //if (strlsope == "submit")
                    //{
                    //    bsp = false;
                    //    JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), progse.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus");
                    //    bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                    //    if (!bsp)
                    //    {
                    //        return Fail("提交失败，启动工作流异常");
                    //    }
                    //}

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(progse, strope, GetUserId());
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(progse.id))
                    {
                        throw new Exception("id不能为空");
                    }

                    CProManageGS jhe = await TranstionRule.FindEntityByKey<CProManageGS>(progse.id);
                    if (null == jhe)
                    {
                        throw new Exception("根据id查询不到概算节点");
                    }
                    else
                    {
                        string pcid = jhe.pcid;
                        string pid = jhe.pid;
                        if (pid != "0")
                        {
                            CProManageGSpc pc = await TranstionRule.FindEntityByKey<CProManageGSpc>(pcid);
                            if (null != pc)
                            {
                                if (pc.status == "2")
                                {
                                    throw new Exception("批次已审核，不能维护");
                                }
                            }
                            else
                            {
                                throw new Exception("节点所在的批次不存在");
                            }
                        }
                    }

                    //bool bsp = true;
                    //if (strlsope == "submit")
                    //{
                    //    bsp = false;
                    //    JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), progse.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus");
                    //    bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                    //    if (!bsp)
                    //    {
                    //        return Fail("提交失败，启动工作流异常");
                    //    }
                    //}

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(progse, strope, GetUserId());
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                //return Fail("响应失败");
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="progs"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProManageGS(dynamic progs)
        {
            //            {
            //                "ope":"add",
            //"progs":{
            //                    "id": "2021051208245413201gs3",
            //  "xmid": "2021051208245413201",
            //  "pid": "2021051208245456901",
            //  "dxmc": "概算3",
            //  "lxspzx": "string",
            //  "lxsprq": "2021-05-12T00:32:33.636Z",
            //  "spl": "string",
            //  "spr": "string",
            //  "remark": "string",
            //  "status": "string",
            //  "createdate": "2021-05-12T00:32:33.637Z",
            //  "createuser": "string",
            //  "gspsje": 100,
            //  "zt": "string",
            //  "units": "个",
            //  "nums": 1,
            //  "prices": 100
            //}
            //            }


            string strope = "add";
            CProManageGS progse = null;

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)progs;

                //获取方法
                strope = progs.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                progse = job["progs"].ToObject<CProManageGS>();

                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "submit")// && strope != "submit"
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }



            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(progse.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProManageGS jhe = await TranstionRule.FindEntityByKey<CProManageGS>(progse.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    progse.status = BaseEditPower.GetSPEnumValue("待审核");
                }



                if (strope == "add")
                {
                    string strid = CommonHelper.GetUniqueId().ToString();
                    progse.id = strid;
                    progse.createuser = GetUserId();

                    if (strlsope != "submit")
                        progse.status = BaseEditPower.GetSPEnumValue("待提交");
                    progse.remark = "1";

                    if (string.IsNullOrEmpty(progse.pid))
                    {
                        throw new Exception("概算信息pid不能为空");
                    }
                    //if (string.IsNullOrEmpty(progse.pid))
                    //{
                    //    throw new Exception("概算信息pid不能为空");
                    //}

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        CProManage xme = await TranstionRule.FindEntityByKey<CProManage>(progse.xmid);
                        if (null == xme)
                        {
                            return Fail("概算信息xmid检索不到数据");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算.ToString(), progse.xmid, progse.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = progse.gsbm, amount = progse.gspsje?.ToString(), content = "[项目概算]" + xme.xmmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), progse.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(progse, strope, GetUserId());
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(progse.id))
                    {
                        throw new Exception("id不能为空");
                    }

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        bsp = false;

                        //string strsql = "select * from CProManage where id = (select xmid from CProManageGSpc where id = '2021081610022201701')";
                        //CProManage xme = await TranstionRule.FindEntityByKey<CProManage>(strsql);
                        //if (null == xme)
                        //{
                        //    return Fail("概算信息xmid检索不到数据");
                        //}

                        CProManage xme = await TranstionRule.FindEntityByKey<CProManage>(progse.xmid);
                        if (null == xme)
                        {
                            return Fail("概算信息xmid检索不到数据");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算.ToString(), progse.xmid, progse.id);
                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = progse.gsbm, amount = progse.gspsje?.ToString(), content = "[项目概算]" + xme.xmmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), progse.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);

                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(progse, strope, GetUserId());
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                //return Fail("响应失败");
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="progs"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertCProManageGSPC(dynamic progs)
        {
            string strope = "add";
            List<CProManageGS> progse = null;
            CProManageGSpc pc = new CProManageGSpc();


            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)progs;

                //获取方法
                strope = progs.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                progse = job["progs"].ToObject<List<CProManageGS>>();

                pc = job["pc"].ToObject<CProManageGSpc>();

                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }



            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(pc.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProManageGSpc jhe = await TranstionRule.FindEntityByKey<CProManageGSpc>(pc.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }

                    pc.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(pc.xmid))
                    {
                        throw new Exception("概算批次xmid不能为空");
                    }

                    for (int i = 0; i < progse.Count; i++)
                    {
                        if (null == progse[i].childs || progse[i].childs.Count <= 0)
                        {
                            throw new Exception("概算批次类型" + progse[i].dxmc + "下无概算节点");
                        }
                    }


                    string strid = CommonHelper.GetUniqueId().ToString();
                    pc.id = strid;
                    pc.createuser = GetUserName();
                    pc.gspcbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(progs), await GetICApiInfo());

                    //单独概算明细编码赋值
                    decimal dje = 0;
                    for (int i = 0; i < progse.Count; i++)
                    {
                        progse[i].gsbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算明细.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(progs), await GetICApiInfo());
                        for (int c = 0; c < progse[i].childs.Count; c++)
                        {
                            progse[i].childs[c].gsbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算明细.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(progs), await GetICApiInfo());

                            //统计概算金额
                            dje += progse[i].childs[c].gspsje ?? 0;
                        }
                    }


                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(pc.id, filecodes, await GetICApiInfo());

                    if (strlsope != "submit")
                        pc.status = BaseEditPower.GetSPEnumValue("待提交");
                    pc.remark = "1";

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        pc.tjr = GetUserName();
                        pc.tjsj = DateTime.Now;

                        bsp = false;

                        CProManage xme = await TranstionRule.FindEntityByKey<CProManage>(pc.xmid);
                        if (null == xme)
                        {
                            return Fail("概算信息xmid检索不到数据");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算.ToString(), pc.xmid, pc.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = pc.gspcbm, amount = dje.ToString(), content = "[项目概算]" + xme.xmmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), pc.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        pc.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))

                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(pc, progse, strope, GetUserId());
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(pc.id))
                    {
                        throw new Exception("id不能为空");
                    }

                    CProManageGSpc jhe = await TranstionRule.FindEntityByKey<CProManageGSpc>(pc.id);
                    if (null == jhe)
                    {
                        throw new Exception("根据pcid检索不到概算批次信息");
                    }
                    else
                    {
                        pc.xmid = jhe.xmid;
                    }


                    decimal dje = 0;
                    for (int i = 0; i < progse.Count; i++)
                    {
                        if (string.IsNullOrEmpty(progse[i].gsbm))
                            progse[i].gsbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算明细.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(progs), await GetICApiInfo());
                        
                        for (int c = 0; c < progse[i].childs.Count; c++)
                        {
                            if (string.IsNullOrEmpty(progse[i].childs[c].gsbm))
                                progse[i].childs[c].gsbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算明细.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(progs), await GetICApiInfo());


                            dje += progse[i].childs[c].gspsje ?? 0;
                        }
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(pc.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        pc.tjr = GetUserName();
                        pc.tjsj = DateTime.Now;

                        bsp = false;

                        CProManage xme = await TranstionRule.FindEntityByKey<CProManage>(pc.xmid);
                        if (null == xme)
                        {
                            return Fail("概算信息xmid检索不到数据");
                        }

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算.ToString(), pc.xmid, pc.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = jhe.gspcbm, amount = dje.ToString(), content = "[项目概算]" + xme.xmmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), pc.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        //if (!bsp)
                        string strInstanceId = await JavaApi.startInstanceJavaAPIStr(spl, await GetICApiInfo());
                        pc.spl = strInstanceId;
                        if (strInstanceId.StartsWith("err"))
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(pc, progse, strope, GetUserId());
                }
                return Success("成功");
            }
            catch (Exception ex)
            {
                //return Fail("响应失败");
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 插入修改
        /// </summary>
        /// <param name="progs"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> InsertCProManageGSPCBY(dynamic progs)
        {
            string strope = "add";
            List<CProManageGS> progse = null;
            CProManageGSpc pc = new CProManageGSpc();


            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)progs;

                //获取方法
                strope = progs.ope;
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                progse = job["progs"].ToObject<List<CProManageGS>>();

                pc = job["pc"].ToObject<CProManageGSpc>();

                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }



            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(pc.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProManageGSpc jhe = await TranstionRule.FindEntityByKey<CProManageGSpc>(pc.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }

                    pc.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(pc.xmid))
                    {
                        throw new Exception("概算批次xmid不能为空");
                    }


                    string strid = CommonHelper.GetUniqueId().ToString();
                    pc.id = strid;
                    pc.createuser = GetUserId();

                    if (strlsope != "submit")
                        pc.status = BaseEditPower.GetSPEnumValue("待提交");
                    pc.remark = "1";

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        pc.tjr = GetUserName();
                        pc.tjsj = DateTime.Now;

                        bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), pc.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus");
                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(pc, progse, strope, GetUserId());
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(pc.id))
                    {
                        throw new Exception("id不能为空");
                    }
                    //if (string.IsNullOrEmpty(pc.xmid))
                    //{
                    //    throw new Exception("概算批次xmid不能为空");
                    //}

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        pc.tjr = GetUserName();
                        pc.tjsj = DateTime.Now;

                        bsp = false;
                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算.ToString(), pc.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(progs), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus");
                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    await BusinessRule.ProGaiSuanRule.InsertCProManageGS(pc, progse, strope, GetUserId());
                }
                return Success("成功");
            }
            catch (Exception ex)
            {
                //return Fail("响应失败");
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="dxid"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProManageGS(string dxid)
        {
            try
            {
                await BusinessRule.ProGaiSuanRule.DeleteCProManageGS(dxid);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 删除多条数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProManageGSMulti(Root ids)
        {
            try
            {
                await BusinessRule.ProGaiSuanRule.DeleteCProManageGSMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 删除多条概算批次
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteCProManageGSPCMulti(Root ids)
        {
            try
            {
                await BusinessRule.ProGaiSuanRule.DeleteCProManageGSPCMulti(ids);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        ///// <summary>
        ///// 概算变更
        ///// </summary>
        ///// <param name="gsid"></param>
        ///// <param name="xmid"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> GSChange(string gsid, string xmid)
        //{
        //    try
        //    {
        //        await BusinessRule.ProGaiSuanRule.GSChange(gsid, xmid);

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}

        #endregion

        #region 概算变更

        [HttpGet]
        //[Authorize(Policy = "TestPolicy")]
        //[AllowAnonymous]
        public async Task<IActionResult> GetGSBGIndexList(string formCode, string xmmc, string status, string bgxz, string bgmc,string dxmc, string current = "1", string size = "20", string sort = "desc", string column = "id")
        {
            try
            {
                dynamic dye = new ExpandoObject();

                //ProGaiSuanPCQuerry querry = new ProGaiSuanPCQuerry();
                //基础属性
                dye.size = size;
                dye.current = current;
                dye.sort = sort;
                dye.column = column;

                dye.Xmmc = xmmc;
                dye.Status = status;
                dye.bgxz = bgxz;
                dye.formCode = formCode;

                dye.bgmc = bgmc;
                dye.dxmc = dxmc;
                

                (IEnumerable<dynamic>, int) SelectTable = await ProGaiSuanRule.GetGSBGIndexList(dye, await GetDepId());//GetUserId()

                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    list.Add(id);
                }

                _logger.Debug("调用审批" + list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug("审批返回" + spitems.ToJson());


                foreach (dynamic item in SelectTable.Item1)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                return Success(pa);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取概算下面的变更列表
        /// </summary>
        /// <param name="strgsid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSBGList(string strgsid)//根据概算id获取变更列表
        {
            try
            {
                DataTable SelectTable = await ProGaiSuanRule.GetGSBGList(strgsid);
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取计划变更列表
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpGet]
        //[AllowAnonymous]
        public async Task<IActionResult> GetGSBGListByXmid(string formCode, string xmid)//根据变更id获取变更列表
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSBGListByxmid(xmid);


                List<string> list = new List<string>();
                foreach (dynamic item in SelectTable)
                {
                    string id = item.id;
                    list.Add(id);
                }

                _logger.Debug("调用审批" + list.ToJson());
                List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(formCode, GetUserAccount(), list, await GetICApiInfo());
                _logger.Debug("审批返回" + spitems.ToJson());


                foreach (dynamic item in SelectTable)
                {
                    string id = item.id;
                    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();

                    item.panguData = GetPanGudData(spstatus, item.spstatus);
                }

                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }

        /// <summary>
        /// 获取计划变更列表
        /// </summary>
        /// <param name="bgid"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetGSBGEntity(string bgid)//根据变更id获取变更列表
        {
            try
            {
                var SelectTable = await ProGaiSuanRule.GetGSBGByid(bgid);
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;
                return Success(SelectTable);
            }
            catch (Exception)
            {
                return Fail("响应失败");
            }
        }



        /// <summary>
        /// 新增概算变更
        /// </summary>
        /// <param name="gsbgjson"></param>
        /// <returns></returns>
        [HttpPost]
        //[AllowAnonymous]
        public async Task<IActionResult> InsertGSBG(dynamic gsbgjson)//
        {
            string strope = "add";
            CProManageGSbgS gsbg = new CProManageGSbgS();
            //List<CProManageTZXM> tzxmids = new List<CProManageTZXM>();

            //添加附件上传
            FileUploadent filecodes = new FileUploadent();
            try
            {
                JObject job = (JObject)gsbgjson;

                //获取方法
                strope = gsbgjson.ope ?? "";
                strope = strope.ToLower();

                //获取实体类 这样复杂类型不用定义实体类
                gsbg = job["gsbg"].ToObject<CProManageGSbgS>();

                //if (null != job["tzxmids"])
                //    tzxmids = job["tzxmids"].ToObject<List<CProManageTZXM>>();

                //接收附件列表
                if (null != job["apiargs"])
                    filecodes = job["apiargs"].ToObject<FileUploadent>();


                if (strope != "add" && strope != "edit" && strope != "approved" && strope != "submit")
                {
                    return Fail("参数ope 不合法");
                }

            }
            catch (Exception ex)
            {
                return Fail("参数转换出错：" + ex.Message);
            }

            try
            {
                string strlsope = strope;
                if (strope == "submit")
                {
                    if (string.IsNullOrEmpty(gsbg.id))//完成新增
                    {
                        strope = "add";
                    }
                    else
                    {
                        CProManageGSbgS jhe = await TranstionRule.FindEntityByKey<CProManageGSbgS>(gsbg.id);
                        if (null == jhe)
                        {
                            strope = "add";
                        }
                        else
                        {
                            strope = "edit";
                        }
                    }
                    gsbg.status = BaseEditPower.GetSPEnumValue("待审核");
                }

                if (strope == "add")
                {
                    if (string.IsNullOrEmpty(gsbg.gsid))
                    {
                        return Fail("变更关联的概算id不能为空");
                    }
                    if (gsbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }

                    //重新赋值一个新id
                    gsbg.id = CommonHelper.GetUniqueId().ToString();
                    gsbg.createuser = GetUserId();

                    gsbg.bgbm = await JavaApi.BusinessBMJavaAPI(BaseEditPower.listTableName[BaseEditPower.TableName.概算变更.ToString()], Newtonsoft.Json.JsonConvert.SerializeObject(gsbgjson), await GetICApiInfo());



                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(gsbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        gsbg.tbsj = DateTime.Now;


                        dynamic dd = await ProGaiSuanRule.GetGSBGScale(gsbg);
                        gsbgjson.bl = dd.bl;


                        bsp = false;
                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算变更.ToString(), gsbg.gsid, gsbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = gsbg.bgbm, amount = gsbg.sqje?.ToString(), content = "[概算变更]" + gsbg.bgmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算变更.ToString(), gsbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(gsbgjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(gsbg.id, filecodes, await GetICApiInfo());

                    //新增投资计划
                    await ProGaiSuanRule.InsertGSBG(gsbg, "add");
                }
                else if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(gsbg.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }
                    if (string.IsNullOrEmpty(gsbg.gsid))
                    {
                        return Fail("变更关联的概算id不能为空");
                    }
                    if (gsbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }

                    //这里先绑定附件
                    await JavaApi.UploadFileJavaAPI(gsbg.id, filecodes, await GetICApiInfo());

                    bool bsp = true;
                    if (strlsope == "submit")
                    {
                        gsbg.tbsj = DateTime.Now;

                        dynamic dd = await ProGaiSuanRule.GetGSBGScale(gsbg);
                        gsbgjson.bl = dd.bl;

                        bsp = false;
                        //CProManageGSbgS jhe = await TranstionRule.FindEntityByKey<CProManageGSbgS>(gsbg.id);
                        //if (null == jhe)
                        //{
                        //    return Fail("根据id未检索到竣工信息");
                        //}

                        var url = BaseEditPower.GetSPDetailUrlS(BaseEditPower.TableName.概算变更.ToString(), gsbg.gsid, gsbg.id);

                        JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = gsbg.bgbm, amount = gsbg.sqje?.ToString(), content = "[概算变更]" + gsbg.bgmc, deptName = GetUserDeptName() };

                        JavaApi.SPLEnt spl = new JavaApi.SPLEnt(BaseEditPower.TableName.概算变更.ToString(), gsbg.id, filecodes.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(gsbgjson), "http://ic-xmzc/netapi/ProTZJH/UpdateStatus", url.Item1, url.Item2, _description);
                        bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                        if (!bsp)
                        {
                            return Fail("提交失败，启动工作流异常");
                        }
                    }

                    //新增投资计划
                    await ProGaiSuanRule.InsertGSBG(gsbg, "edit");
                }
                else if (strope == "approved")
                {
                    if (string.IsNullOrEmpty(gsbg.id))
                    {
                        return Fail("概算变更编号不能为空");
                    }
                    if (gsbg.bgsdje == 0)
                    {
                        return Fail("变更审定金额不能为空或零");
                    }

                    //获取概算的当前状态
                    CProManageGSbgS gsBGe = await TranstionRule.FindEntityByKey<CProManageGSbgS>(gsbg.id);// await ProGaiSuanRule.FindEntityGSBG(gsbg.id);
                    string strstatus = "";
                    if (null != gsBGe)
                    {
                        strstatus = gsBGe.status ?? "";
                    }

                    if (strstatus == "2")
                    {

                        //这里先绑定附件
                        await JavaApi.UploadFileJavaAPI(gsbg.id, filecodes, await GetICApiInfo());
                        //新增投资计划
                        await ProGaiSuanRule.InsertGSBG(gsbg, "edit");
                    }
                    else
                    {
                        return Fail("数据状态为" + strstatus + ",未审核完成");
                    }
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 修改概算变更
        /// </summary>
        /// <param name="gsbg"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UpdateGSBG(CProManageGSbgS gsbg, string strlx = "xxx")//
        {
            try
            {
                string strope = strlx.ToLower();
                if (strope != "edit" && strope != "approved")
                {
                    return Fail("strlx参数错误");
                }

                if (strope == "edit")
                {
                    if (string.IsNullOrEmpty(gsbg.id))
                    {
                        return Fail("需要修改的变更id不能为空");
                    }
                    if (string.IsNullOrEmpty(gsbg.gsid))
                    {
                        return Fail("变更关联的概算id不能为空");
                    }
                    if (gsbg.sqje == 0)
                    {
                        return Fail("变更金额不能为空或零");
                    }


                    //新增投资计划
                    await ProGaiSuanRule.InsertGSBG(gsbg, "edit");
                }
                else if (strope == "approved")
                {
                    if (string.IsNullOrEmpty(gsbg.id))
                    {
                        return Fail("概算变更编号不能为空");
                    }
                    if (gsbg.bgsdje == 0)
                    {
                        return Fail("变更审定金额不能为空或零");
                    }

                    //获取概算的当前状态
                    CProManageGSbgS gsBGe = await TranstionRule.FindEntityByKey<CProManageGSbgS>(gsbg.id);// await ProGaiSuanRule.FindEntityGSBG(gsbg.id);
                    string strstatus = "";
                    if (null != gsBGe)
                    {
                        strstatus = gsBGe.status ?? "";
                    }

                    if (strstatus == "2")
                    {
                        //新增投资计划
                        await ProGaiSuanRule.InsertGSBG(gsbg, "edit");
                    }
                    else
                    {
                        return Fail("数据状态为" + strstatus + ",未审核完成");
                    }
                }


                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DelGSBG(string bgid)//
        {
            try
            {
                if (string.IsNullOrEmpty(bgid))
                {
                    return Fail("概算变更编号不能为空");
                }

                //if (!await BaseEditPower.GetEditPower(bgid, BaseEditPower.TableName.投资计划结转))
                //{
                //    return Fail("响应失败:请确认数据权限");
                //    //throw new Exception("请确认数据权限");
                //}


                //新增投资计划
                if (await ProGaiSuanRule.DeleteGSBG(bgid) > 0)
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("影响行数为0");
                }

            }
            catch (Exception ex)
            {
                return Fail("响应失败:" + ex.Message);
            }
        }

        #endregion

        //#region 概算预测（预测列表，保存修改预测，预测明细-新增修改删除）
        ///// <summary>
        ///// 预测列表
        ///// </summary>
        ///// <param name="xmid"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetGSYCByXmid(string xmid)
        //{
        //    try
        //    {
        //        var SelectTable = await ProGaiSuanRule.GetGSYCByXmid(xmid);
        //        return Success(SelectTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}
        ///// <summary>
        ///// 根据xmid获取所有预测明细
        ///// </summary>
        ///// <param name="keyValue"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetGSYCMXByXmid(string xmid, string current = "1", string size = "20", string sort = "desc", string column = "czsj")
        //{
        //    try
        //    {
        //        CProManageGSYCQuerry querry = new CProManageGSYCQuerry();
        //        //基础属性
        //        querry.size = CommonHelper.ParseInt(size);
        //        querry.current = CommonHelper.ParseInt(current);
        //        querry.sort = sort;
        //        querry.column = column;
        //        querry.xmid = xmid;

        //        (DataTable, int) SelectTable = await ProGaiSuanRule.GetGSYCMXByXmid(querry, xmid);
        //        Page pa = new Page();
        //        pa.records = SelectTable.Item1;
        //        pa.total = SelectTable.Item2;
        //        return Success(pa);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}
        ///// <summary>
        ///// 根据预测id获取单条预测
        ///// </summary>
        ///// <param name="keyValue"></param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public async Task<IActionResult> GetYCByid(string keyValue)
        //{
        //    try
        //    {
        //        var SelectTable = await ProGaiSuanRule.GetYCByid(keyValue);

        //        return Success(SelectTable);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}
        ///// <summary>
        ///// 插入修改预测
        ///// </summary>
        ///// <param name="progs"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]

        //public async Task<IActionResult> InsertCProManageGSYC(CProManageGSYC progsyc)
        //{
        //    try
        //    {
        //        await BusinessRule.ProGaiSuanRule.InsertCProManageGSYC(progsyc, GetUserId());

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        //return Fail("响应失败");
        //        return Fail(ex.Message);
        //    }
        //}
        ///// <summary>
        ///// 删除多条预测
        ///// </summary>
        ///// <param name="ids"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<IActionResult> DeleteCProManageGSYCMulti(Root ids)
        //{
        //    try
        //    {
        //        await BusinessRule.ProGaiSuanRule.DeleteCProManageGSYCMulti(ids);

        //        return Success("成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        return Fail(ex.Message);
        //    }
        //}
        //#endregion
    }
}
